package client

import (
	"fmt"
	"github.com/gorilla/websocket"
	"sync"
)

// ClientsManager 定义了客户端管理的接口
type ClientsManager interface {
	Set(clientId string, conn *websocket.Conn) error
	Get(clientId string) (*websocket.Conn, error)
	Del(clientId string) error
}

// Clients 实现了 ClientManager 接口
type Clients struct {
	Mu sync.RWMutex
	C  map[string]*websocket.Conn // map[clientId]*websocket.Conn
}

// NewClients 创建一个新的 Clients 实例
func NewClients() *Clients {
	return &Clients{
		C: make(map[string]*websocket.Conn),
	}
}

// Set 将连接与客户端ID关联存储
func (c *Clients) Set(clientId string, conn *websocket.Conn) error {
	c.Mu.Lock()
	defer c.Mu.Unlock()
	c.C[clientId] = conn
	return nil
}

// Get 根据客户端ID获取连接
func (c *Clients) Get(clientId string) (*websocket.Conn, error) {
	c.Mu.Lock()
	defer c.Mu.Unlock()
	conn, exists := c.C[clientId]
	if !exists {
		return nil, fmt.Errorf("client 未找到 clientId: %s", clientId)
	}
	return conn, nil
}

// Del 根据客户端ID删除连接
func (c *Clients) Del(clientId string) error {
	c.Mu.Lock()
	defer c.Mu.Unlock()
	delete(c.C, clientId)
	return nil
}
